import {deleteSysMenu, queryAllMenu, queryMenuById, saveSysMenu} from '@/services/systemManage/menuManage'
import {storePrompt} from '@/store/modules/commonStore'
import {filter} from 'lodash'

export default {
  namespaced: true,
  state: {
    title: '',
    currentCom: '',
    spinning: false,
    treeData: [],
    currentKey: undefined,
    editData: null,
    allTreeData: []
  },
  getters: {
    getTreeData(state) {
      return [{
        key: '菜单',
        title: '菜单',
        disabled: true,
        children: state.treeData
      }]
    }
  },
  actions: {
    async saveMenu({commit, dispatch, state}, payload) {
      let {values, url} = payload
      await saveSysMenu(values, url).then((obj) => {
        let {success} = obj.data
        storePrompt(success)
      })
      dispatch('queryAll')
      commit('setState', {name: 'spinning', value: false})
      commit('setState', {name: 'currentCom', value: ''})
    },

    async queryAll({commit}) {
      let info = []
      await queryAllMenu().then((obj) => {
        const {Child, Parent} = obj.data.data
        commit('setState', {name: 'allTreeData', value: [...Child, ...Parent]})
        for (let parent of Parent) {
          let node = {
            key: parent.objectId,
            title: parent.name,
            scopedSlots: {title: 'title'}
          }
          let children = filter(Child, {parentId: parent.objectId}).map((value) => {
            return {
              key: value.objectId,
              title: value.name,
              scopedSlots: {title: 'title'}
            }
          })
          info.push({...node, children})
        }
      })
      commit('setState', {name: 'treeData', value: info})
    },

    async deleteMenu({commit, dispatch}, payload) {
      await deleteSysMenu(payload).then((obj) => {
        let {success} = obj.data
        storePrompt(success)
      })
      commit('setState', {name: 'currentKey', value: ''})
      commit('setState', {name: 'currentCom', value: ''})
      dispatch('queryAll')
    },

    async queryById({commit}, payload) {
      await queryMenuById(payload).then((obj) => {
        commit('setState', {name: 'editData', value: obj.data.data})
      })
    }

  }
}